
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
  <head>
    <meta charset="utf-8" />
    <title>函数式编程指引 &#8212; Python 3.7.8 文档</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="在 Python 3.7.8 文档 中搜索"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="版权所有" href="../copyright.html" />
    <link rel="next" title="日志 HOWTO" href="logging.html" />
    <link rel="prev" title="实现描述器" href="descriptor.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/howto/functional.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
    
    
    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
 

  </head><body>
  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="logging.html" title="日志 HOWTO"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="descriptor.html" title="实现描述器"
             accesskey="P">上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python 常用指引</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="functional-programming-howto">
<h1>函数式编程指引<a class="headerlink" href="#functional-programming-howto" title="永久链接至标题">¶</a></h1>
<dl class="field-list simple">
<dt class="field-odd">作者</dt>
<dd class="field-odd"><p>A. M. Kuchling</p>
</dd>
<dt class="field-even">发布版本</dt>
<dd class="field-even"><p>0.32</p>
</dd>
</dl>
<p>本文档提供恰当的 Python 函数式编程范例，在函数式编程简单的介绍之后，将简单介绍Python中关于函数式编程的特性如 <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> 和 <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a> 以及相关库模块如 <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> 和 <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> 等。</p>
<div class="section" id="introduction">
<h2>概述<a class="headerlink" href="#introduction" title="永久链接至标题">¶</a></h2>
<p>本章介绍函数式编程的基本概念。如您仅想学习 Python 语言的特性，可跳过本章直接查看 <a class="reference internal" href="#functional-howto-iterators"><span class="std std-ref">迭代器</span></a>.</p>
<p>编程语言支持通过以下几种方式来解构具体问题：</p>
<ul class="simple">
<li><p>大多数的编程语言都是 <strong>过程式</strong> 的，所谓程序就是一连串告诉计算机怎样处理程序输入的指令。C、Pascal 甚至 Unix shells 都是过程式语言。</p></li>
<li><p>在 <strong>声明式</strong> 语言中，你编写一个用来描述待解决问题的说明，并且这个语言的具体实现会指明怎样高效的进行计算。 SQL 可能是你最熟悉的声明式语言了。 一个 SQL 查询语句描述了你想要检索的数据集，并且 SQL 引擎会决定是扫描整张表还是使用索引，应该先执行哪些子句等等。</p></li>
<li><p><strong>面向对象</strong> 程序会操作一组对象。 对象拥有内部状态，并能够以某种方式支持请求和修改这个内部状态的方法。Smalltalk 和 Java 都是面向对象的语言。 C++ 和 Python 支持面向对象编程，但并不强制使用面向对象特性。</p></li>
<li><p><strong>函数式</strong> 编程则将一个问题分解成一系列函数。 理想情况下，函数只接受输入并输出结果，对一个给定的输入也不会有影响输出的内部状态。 著名的函数式语言有 ML 家族（Standard ML，Ocaml 以及其他变种）和 Haskell。</p></li>
</ul>
<p>一些语言的设计者选择强调一种特定的编程方式。 这通常会让以不同的方式来编写程序变得困难。其他多范式语言则支持几种不同的编程方式。Lisp，C++ 和 Python 都是多范式语言；使用这些语言，你可以编写主要为过程式，面向对象或者函数式的程序和函数库。在大型程序中，不同的部分可能会采用不同的方式编写；比如 GUI 可能是面向对象的而处理逻辑则是过程式或者函数式。</p>
<p>在函数式程序里，输入会流经一系列函数。每个函数接受输入并输出结果。函数式风格反对使用带有副作用的函数，这些副作用会修改内部状态，或者引起一些无法体现在函数的返回值中的变化。完全不产生副作用的函数被称作“纯函数”。消除副作用意味着不能使用随程序运行而更新的数据结构；每个函数的输出必须只依赖于输入。</p>
<p>一些语言对纯洁性要求非常严格，以至于没有像 <code class="docutils literal notranslate"><span class="pre">a=3</span></code> 或 <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">a</span> <span class="pre">+</span> <span class="pre">b</span></code> 这样的赋值表达式，但是完全消除副作用非常困难。 比如，显示在屏幕上或者写到磁盘文件中都是副作用。举个例子，在 Python 里，调用函数 <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> 或者 <a class="reference internal" href="../library/time.html#time.sleep" title="time.sleep"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.sleep()</span></code></a> 并不会返回有用的结果；它们的用途只在于副作用，向屏幕发送一段文字或暂停一秒钟。</p>
<p>函数式风格的 Python 程序并不会极端到消除所有 I/O 或者赋值的程度；相反，他们会提供像函数式一样的接口，但会在内部使用非函数式的特性。比如，函数的实现仍然会使用局部变量，但不会修改全局变量或者有其他副作用。</p>
<p>函数式编程可以被认为是面向对象编程的对立面。对象就像是颗小胶囊，包裹着内部状态和随之而来的能让你修改这个内部状态的一组调用方法，以及由正确的状态变化所构成的程序。函数式编程希望尽可能地消除状态变化，只和流经函数的数据打交道。在 Python 里你可以把两种编程方式结合起来，在你的应用（电子邮件信息，事务处理）中编写接受和返回对象实例的函数。</p>
<p>函数式设计在工作中看起来是个奇怪的约束。为什么你要消除对象和副作用呢？不过函数式风格有其理论和实践上的优点：</p>
<ul class="simple">
<li><p>形式证明。</p></li>
<li><p>模块化。</p></li>
<li><p>组合性。</p></li>
<li><p>易于调试和测试。</p></li>
</ul>
<div class="section" id="formal-provability">
<h3>形式证明<a class="headerlink" href="#formal-provability" title="永久链接至标题">¶</a></h3>
<p>一个理论上的优点是，构造数学证明来说明函数式程序是正确的相对更容易些。</p>
<p>很长时间，研究者们对寻找证明程序正确的数学方法都很感兴趣。这和通过大量输入来测试，并得出程序的输出基本正确，或者阅读一个程序的源代码然后得出代码看起来没问题不同；相反，这里的目标是一个严格的证明，证明程序对所有可能的输入都能给出正确的结果。</p>
<p>证明程序正确性所用到的技术是写出 <strong>不变量</strong>，也就是对于输入数据和程序中的变量永远为真的特性。然后对每行代码，你说明这行代码执行前的不变量 X 和 Y 以及执行后稍有不同的不变量 X' 和 Y' 为真。如此一直到程序结束，这时候在程序的输出上，不变量应该会与期望的状态一致。</p>
<p>函数式编程之所以要消除赋值，是因为赋值在这个技术中难以处理；赋值可能会破坏赋值前为真的不变量，却并不产生任何可以传递下去的新的不变量。</p>
<p>不幸的是，证明程序的正确性很大程度上是经验性质的，而且和 Python 软件无关。即使是微不足道的程序都需要几页长的证明；一个中等复杂的程序的正确性证明会非常庞大，而且，极少甚至没有你日常所使用的程序（Python 解释器，XML 解析器，浏览器）的正确性能够被证明。即使你写出或者生成一个证明，验证证明也会是一个问题；里面可能出了差错，而你错误地相信你证明了程序的正确性。</p>
</div>
<div class="section" id="modularity">
<h3>模块化<a class="headerlink" href="#modularity" title="永久链接至标题">¶</a></h3>
<p>函数式编程的一个更实用的优点是，它强制你把问题分解成小的方面。因此程序会更加模块化。相对于一个进行了复杂变换的大型函数，一个小的函数更明确，更易于编写, 也更易于阅读和检查错误。</p>
</div>
<div class="section" id="ease-of-debugging-and-testing">
<h3>易于调试和测试<a class="headerlink" href="#ease-of-debugging-and-testing" title="永久链接至标题">¶</a></h3>
<p>测试和调试函数式程序相对来说更容易。</p>
<p>调试很简单是因为函数通常都很小而且清晰明确。当程序无法工作的时候，每个函数都是一个可以检查数据是否正确的接入点。你可以通过查看中间输入和输出迅速找到出错的函数。</p>
<p>测试更容易是因为每个函数都是单元测试的潜在目标。在执行测试前，函数并不依赖于需要重现的系统状态；相反，你只需要给出正确的输入，然后检查输出是否和期望的结果一致。</p>
</div>
<div class="section" id="composability">
<h3>组合性<a class="headerlink" href="#composability" title="永久链接至标题">¶</a></h3>
<p>当你编写函数式风格的程序时，你会写出很多带有不同输入和输出的函数。其中一些不可避免地会局限于特定的应用，但其他的却可以广泛的用在程序中。举例来说，一个接受文件夹目录返回所有文件夹中的 XML 文件的函数； 或是一个接受文件名，然后返回文件内容的函数，都可以应用在很多不同的场合。</p>
<p>久而久之你会形成一个个人工具库。通常你可以重新组织已有的函数来组成新的程序，然后为当前的工作写一些特殊的函数。</p>
</div>
</div>
<div class="section" id="iterators">
<span id="functional-howto-iterators"></span><h2>迭代器<a class="headerlink" href="#iterators" title="永久链接至标题">¶</a></h2>
<p>我会从 Python 的一个语言特性， 编写函数式风格程序的重要基石开始说起：迭代器。</p>
<p>迭代器是一个表示数据流的对象；这个对象每次只返回一个元素。Python 迭代器必须支持 <a class="reference internal" href="../library/stdtypes.html#iterator.__next__" title="iterator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> 方法；这个方法不接受参数，并总是返回数据流中的下一个元素。如果数据流中没有元素，<a class="reference internal" href="../library/stdtypes.html#iterator.__next__" title="iterator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> 会抛出 <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> 异常。迭代器未必是有限的；完全有理由构造一个输出无限数据流的迭代器。</p>
<p>内置的 <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> 函数接受任意对象并试图返回一个迭代器来输出对象的内容或元素，并会在对象不支持迭代的时候抛出 <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> 异常。Python 有几种内置数据类型支持迭代，最常见的就是列表和字典。如果一个对象能生成迭代器，那么它就会被称作 <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a>。</p>
<p>你可以手动试验迭代器的接口。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span>  
<span class="go">&lt;...iterator object at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span><span class="o">.</span><span class="fm">__next__</span><span class="p">()</span>  <span class="c1"># same as next(it)</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">StopIteration</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Python 有不少要求使用可迭代的对象的地方，其中最重要的就是 <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> 表达式。在表达式 <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">X</span> <span class="pre">in</span> <span class="pre">Y</span></code>，Y 要么自身是一个迭代器，要么能够由 <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> 创建一个迭代器。以下两种表达是等价的:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">iter</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>

<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">obj</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
<p>可以用 <a class="reference internal" href="../library/stdtypes.html#list" title="list"><code class="xref py py-func docutils literal notranslate"><span class="pre">list()</span></code></a> 或 <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">tuple()</span></code></a> 这样的构造函数把迭代器具体化成列表或元组:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">iterator</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">iterator</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span>
<span class="go">(1, 2, 3)</span>
</pre></div>
</div>
<p>序列的解压操作也支持迭代器：如果你知道一个迭代器能够返回 N 个元素，你可以把他们解压到有 N 个元素的元组:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">iterator</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span> <span class="o">=</span> <span class="n">iterator</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span>
<span class="go">(1, 2, 3)</span>
</pre></div>
</div>
<p>像 <a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> 和 <a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a> 这样的内置函数可以接受单个迭代器参数，然后返回其中最大或者最小的元素。<code class="docutils literal notranslate"><span class="pre">&quot;in&quot;</span></code> 和 <code class="docutils literal notranslate"><span class="pre">&quot;not</span> <span class="pre">in&quot;</span></code> 操作也支持迭代器：如果能够在迭代器 iterator 返回的数据流中找到 X 的话，则``X in iterator`` 为真。很显然，如果迭代器是无限的，这么做你就会遇到问题；<a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> 和 <a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a> 永远也不会返回；如果元素 X 也不出现在数据流中，<code class="docutils literal notranslate"><span class="pre">&quot;in&quot;</span></code> 和 <code class="docutils literal notranslate"><span class="pre">&quot;not</span> <span class="pre">in&quot;</span></code> 操作同样也永远不会返回。</p>
<p>注意你只能在迭代器中顺序前进；没有获取前一个元素的方法，除非重置迭代器，或者重新复制一份。迭代器对象可以提供这些额外的功能，但迭代器协议只明确了 <a class="reference internal" href="../library/stdtypes.html#iterator.__next__" title="iterator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> 方法。函数可能因此而耗尽迭代器的输出，如果你要对同样的数据流做不同的操作，你必须重新创建一个迭代器。</p>
<div class="section" id="data-types-that-support-iterators">
<h3>支持迭代器的数据类型<a class="headerlink" href="#data-types-that-support-iterators" title="永久链接至标题">¶</a></h3>
<p>我们已经知道列表和元组支持迭代器。实际上，Python 中的任何序列类型，比如字符串，都自动支持创建迭代器。</p>
<p>对字典调用 <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> 会返回一个遍历字典的键的迭代器:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Jan&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;Feb&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;Mar&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;Apr&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;May&#39;</span><span class="p">:</span> <span class="mi">5</span><span class="p">,</span> <span class="s1">&#39;Jun&#39;</span><span class="p">:</span> <span class="mi">6</span><span class="p">,</span>
<span class="gp">... </span>     <span class="s1">&#39;Jul&#39;</span><span class="p">:</span> <span class="mi">7</span><span class="p">,</span> <span class="s1">&#39;Aug&#39;</span><span class="p">:</span> <span class="mi">8</span><span class="p">,</span> <span class="s1">&#39;Sep&#39;</span><span class="p">:</span> <span class="mi">9</span><span class="p">,</span> <span class="s1">&#39;Oct&#39;</span><span class="p">:</span> <span class="mi">10</span><span class="p">,</span> <span class="s1">&#39;Nov&#39;</span><span class="p">:</span> <span class="mi">11</span><span class="p">,</span> <span class="s1">&#39;Dec&#39;</span><span class="p">:</span> <span class="mi">12</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">m</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">m</span><span class="p">[</span><span class="n">key</span><span class="p">])</span>
<span class="go">Jan 1</span>
<span class="go">Feb 2</span>
<span class="go">Mar 3</span>
<span class="go">Apr 4</span>
<span class="go">May 5</span>
<span class="go">Jun 6</span>
<span class="go">Jul 7</span>
<span class="go">Aug 8</span>
<span class="go">Sep 9</span>
<span class="go">Oct 10</span>
<span class="go">Nov 11</span>
<span class="go">Dec 12</span>
</pre></div>
</div>
<p>注意从 Python 3.7 开始，字典的遍历顺序一定和输入顺序一样。先前的版本并没有明确这一点，所以不同的实现可能不一致。</p>
<p>对字典使用 <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> 总是会遍历键，但字典也有返回其他迭代器的方法。如果你只遍历值或者键/值对，你可以明确地调用 <a class="reference internal" href="../library/stdtypes.html#dict.values" title="dict.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code></a> 或 <a class="reference internal" href="../library/stdtypes.html#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code></a> 方法得到合适的迭代器。</p>
<p><a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">dict()</span></code></a> 构造函数可以接受一个迭代器，然后返回一个有限的 <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> 元组的数据流:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;Italy&#39;</span><span class="p">,</span> <span class="s1">&#39;Rome&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;France&#39;</span><span class="p">,</span> <span class="s1">&#39;Paris&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;US&#39;</span><span class="p">,</span> <span class="s1">&#39;Washington DC&#39;</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dict</span><span class="p">(</span><span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">))</span>
<span class="go">{&#39;Italy&#39;: &#39;Rome&#39;, &#39;France&#39;: &#39;Paris&#39;, &#39;US&#39;: &#39;Washington DC&#39;}</span>
</pre></div>
</div>
<p>文件也可以通过调用 <a class="reference internal" href="../library/io.html#io.TextIOBase.readline" title="io.TextIOBase.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> 来遍历，直到穷尽文件中所有的行。这意味着你可以像这样读取文件中的每一行:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">file</span><span class="p">:</span>
    <span class="c1"># do something for each line</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>集合可以从可遍历的对象获取内容，也可以让你遍历集合的元素:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">S</span> <span class="o">=</span> <span class="p">{</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">13</span><span class="p">}</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">S</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="generator-expressions-and-list-comprehensions">
<h2>生成器表达式和列表推导式<a class="headerlink" href="#generator-expressions-and-list-comprehensions" title="永久链接至标题">¶</a></h2>
<p>迭代器的输出有两个很常见的使用方式，1) 对每一个元素执行操作，2) 选择一个符合条件的元素子集。比如，给定一个字符串列表，你可能想去掉每个字符串尾部的空白字符，或是选出所有包含给定子串的字符串。</p>
<p>列表推导式和生成器表达时（简写：&quot;listcomps&quot; 和 &quot;genexps&quot;）让这些操作更加简明，这个形式借鉴自函数式程序语言 Haskell（<a class="reference external" href="https://www.haskell.org/">https://www.haskell.org/</a>）。你可以用以下代码去掉一个字符串流中的所有空白字符:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">line_list</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;  line 1</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;line 2  </span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="o">...</span><span class="p">]</span>

<span class="c1"># Generator expression -- returns iterator</span>
<span class="n">stripped_iter</span> <span class="o">=</span> <span class="p">(</span><span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">line_list</span><span class="p">)</span>

<span class="c1"># List comprehension -- returns list</span>
<span class="n">stripped_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">line_list</span><span class="p">]</span>
</pre></div>
</div>
<p>你可以加上条件语句 <code class="docutils literal notranslate"><span class="pre">&quot;if&quot;</span></code> 来选取特定的元素:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">stripped_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">line_list</span>
                 <span class="k">if</span> <span class="n">line</span> <span class="o">!=</span> <span class="s2">&quot;&quot;</span><span class="p">]</span>
</pre></div>
</div>
<p>通过列表推导式，你会获得一个 Python 列表；<code class="docutils literal notranslate"><span class="pre">stripped_list</span></code> 就是一个包含所有结果行的列表，并不是迭代器。 生成器表达式会返回一个迭代器，它在必要的时候计算结果，避免一次性生成所有的值。 这意味着，如果迭代器返回一个无限数据流或者大量的数据，列表推导式就不太好用了。 这种情况下生成器表达式会更受青睐。</p>
<p>生成器表达式两边使用圆括号 (&quot;()&quot;) ，而列表推导式则使用方括号 (&quot;[]&quot;)。生成器表达式的形式为:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">(</span> <span class="n">expression</span> <span class="k">for</span> <span class="n">expr</span> <span class="ow">in</span> <span class="n">sequence1</span>
             <span class="k">if</span> <span class="n">condition1</span>
             <span class="k">for</span> <span class="n">expr2</span> <span class="ow">in</span> <span class="n">sequence2</span>
             <span class="k">if</span> <span class="n">condition2</span>
             <span class="k">for</span> <span class="n">expr3</span> <span class="ow">in</span> <span class="n">sequence3</span> <span class="o">...</span>
             <span class="k">if</span> <span class="n">condition3</span>
             <span class="k">for</span> <span class="n">exprN</span> <span class="ow">in</span> <span class="n">sequenceN</span>
             <span class="k">if</span> <span class="n">conditionN</span> <span class="p">)</span>
</pre></div>
</div>
<p>再次说明，列表推导式只有两边的括号不一样（方括号而不是圆括号）。</p>
<p>这些生成用于输出的元素会成为 <code class="docutils literal notranslate"><span class="pre">expression</span></code> 的后继值。其中 <code class="docutils literal notranslate"><span class="pre">if</span></code> 语句是可选的；如果给定的话 <code class="docutils literal notranslate"><span class="pre">expression</span></code> 只会在符合条件时计算并加入到结果中。</p>
<p>生成器表达式总是写在圆括号里面，不过也可以算上调用函数时用的括号。如果你想即时创建一个传递给函数的迭代器，可以这么写:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">obj_total</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">obj</span><span class="o">.</span><span class="n">count</span> <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">list_all_objects</span><span class="p">())</span>
</pre></div>
</div>
<p>其中 <code class="docutils literal notranslate"><span class="pre">for...in</span></code> 语句包含了将要遍历的序列。这些序列并不必须同样长，因为它们会从左往右开始遍历，而 <strong>不是</strong> 同时执行。对每个 <code class="docutils literal notranslate"><span class="pre">sequence1</span></code> 中的元素，<code class="docutils literal notranslate"><span class="pre">sequence2</span></code> 会从头开始遍历。<code class="docutils literal notranslate"><span class="pre">sequence3</span></code> 会对每个 <code class="docutils literal notranslate"><span class="pre">sequence1</span></code> 和 <code class="docutils literal notranslate"><span class="pre">sequence2</span></code> 的元素对开始遍历。</p>
<p>换句话说，列表推导式器是和下面的 Python 代码等价:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">expr1</span> <span class="ow">in</span> <span class="n">sequence1</span><span class="p">:</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">condition1</span><span class="p">):</span>
        <span class="k">continue</span>   <span class="c1"># Skip this element</span>
    <span class="k">for</span> <span class="n">expr2</span> <span class="ow">in</span> <span class="n">sequence2</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">condition2</span><span class="p">):</span>
            <span class="k">continue</span>   <span class="c1"># Skip this element</span>
        <span class="o">...</span>
        <span class="k">for</span> <span class="n">exprN</span> <span class="ow">in</span> <span class="n">sequenceN</span><span class="p">:</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">conditionN</span><span class="p">):</span>
                <span class="k">continue</span>   <span class="c1"># Skip this element</span>

            <span class="c1"># Output the value of</span>
            <span class="c1"># the expression.</span>
</pre></div>
</div>
<p>这说明，如果有多个 <code class="docutils literal notranslate"><span class="pre">for...in</span></code> 语句而没有 <code class="docutils literal notranslate"><span class="pre">if</span></code> 语句，输出结果的长度就是所有序列长度的乘积。如果你的两个列表长度为3，那么输出的列表长度就是9:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">seq1</span> <span class="o">=</span> <span class="s1">&#39;abc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">seq2</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">seq1</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">seq2</span><span class="p">]</span>  
<span class="go">[(&#39;a&#39;, 1), (&#39;a&#39;, 2), (&#39;a&#39;, 3),</span>
<span class="go"> (&#39;b&#39;, 1), (&#39;b&#39;, 2), (&#39;b&#39;, 3),</span>
<span class="go"> (&#39;c&#39;, 1), (&#39;c&#39;, 2), (&#39;c&#39;, 3)]</span>
</pre></div>
</div>
<p>为了不让 Python 语法变得含糊，如果 <code class="docutils literal notranslate"><span class="pre">expression</span></code> 会生成元组，那这个元组必须要用括号括起来。下面第一个列表推导式语法错误，第二个则是正确的:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Syntax error</span>
<span class="p">[</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">seq1</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">seq2</span><span class="p">]</span>
<span class="c1"># Correct</span>
<span class="p">[(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">seq1</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">seq2</span><span class="p">]</span>
</pre></div>
</div>
</div>
<div class="section" id="generators">
<h2>生成器<a class="headerlink" href="#generators" title="永久链接至标题">¶</a></h2>
<p>生成器是一类用来简化编写迭代器工作的特殊函数。普通的函数计算并返回一个值，而生成器返回一个能返回数据流的迭代器。</p>
<p>毫无疑问，你已经对如何在 Python 和 C 中调用普通函数很熟悉了，这时候函数会获得一个创建局部变量的私有命名空间。当函数到达 <code class="docutils literal notranslate"><span class="pre">return</span></code> 表达式时，局部变量会被销毁然后把返回给调用者。之后调用同样的函数时会创建一个新的私有命名空间和一组全新的局部变量。但是，如果在退出一个函数时不扔掉局部变量会如何呢？如果稍后你能够从退出函数的地方重新恢复又如何呢？这就是生成器所提供的；他们可以被看成可恢复的函数。</p>
<p>这里有简单的生成器函数示例:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">generate_ints</span><span class="p">(</span><span class="n">N</span><span class="p">):</span>
<span class="gp">... </span>   <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">N</span><span class="p">):</span>
<span class="gp">... </span>       <span class="k">yield</span> <span class="n">i</span>
</pre></div>
</div>
<p>任何包含了 <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> 关键字的函数都是生成器函数；Python 的 <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> 编译器会在编译的时候检测到并因此而特殊处理。</p>
<p>当你调用一个生成器函数，它并不会返回单独的值，而是返回一个支持生成器协议的生成器对象。当执行 <code class="docutils literal notranslate"><span class="pre">yield</span></code> 表达式时，生成器会输出 <code class="docutils literal notranslate"><span class="pre">i</span></code> 的值，就像 <code class="docutils literal notranslate"><span class="pre">return</span></code> 表达式一样。<code class="docutils literal notranslate"><span class="pre">yield</span></code> 和 <code class="docutils literal notranslate"><span class="pre">return</span></code> 最大的区别在于，到达 <code class="docutils literal notranslate"><span class="pre">yield</span></code> 的时候生成器的执行状态会挂起并保留局部变量。在下一次调用生成器 <a class="reference internal" href="../reference/expressions.html#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> 方法的时候，函数会恢复执行。</p>
<p>这里有一个 <code class="docutils literal notranslate"><span class="pre">generate_ints()</span></code> 生成器的示例:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span> <span class="o">=</span> <span class="n">generate_ints</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span>  
<span class="go">&lt;generator object generate_ints at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">gen</span><span class="p">)</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">gen</span><span class="p">)</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">gen</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">gen</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;stdin&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  File <span class="nb">&quot;stdin&quot;</span>, line <span class="m">2</span>, in <span class="n">generate_ints</span>
<span class="gr">StopIteration</span>
</pre></div>
</div>
<p>同样，你可以写出 <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">generate_ints(5)</span></code>，或者 <code class="docutils literal notranslate"><span class="pre">a,</span> <span class="pre">b,</span> <span class="pre">c</span> <span class="pre">=</span> <span class="pre">generate_ints(3)</span></code>。</p>
<p>在生成器函数里面，<code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">value</span></code> 会触发从 <a class="reference internal" href="../reference/expressions.html#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> 方法抛出 <code class="docutils literal notranslate"><span class="pre">StopIteration(value)</span></code> 异常。一旦抛出这个异常，或者函数结束，处理数据的过程就会停止，生成器也不会再生成新的值。</p>
<p>你可以手动编写自己的类来达到生成器的效果，把生成器的所有局部变量作为实例的成员变量存储起来。比如，可以这么返回一个整数列表：把 <code class="docutils literal notranslate"><span class="pre">self.count</span></code> 设为0，然后通过 <code class="xref py py-meth docutils literal notranslate"><span class="pre">count`()</span></code>。然而，对于一个中等复杂程度的生成器，写出一个相应的类可能会相当繁杂。</p>
<p>包含在 Python 库中的测试套件 <a class="reference external" href="https://github.com/python/cpython/tree/3.7/Lib/test/test_generators.py">Lib/test/test_generators.py</a> 里有很多非常有趣的例子。这里是一个用生成器实现树的递归中序遍历示例。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># A recursive generator that generates Tree leaves in in-order.</span>
<span class="k">def</span> <span class="nf">inorder</span><span class="p">(</span><span class="n">t</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">t</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">left</span><span class="p">):</span>
            <span class="k">yield</span> <span class="n">x</span>

        <span class="k">yield</span> <span class="n">t</span><span class="o">.</span><span class="n">label</span>

        <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">right</span><span class="p">):</span>
            <span class="k">yield</span> <span class="n">x</span>
</pre></div>
</div>
<p>另外两个 <code class="docutils literal notranslate"><span class="pre">test_generators.py</span></code> 中的例子给出了 N 皇后问题（在 NxN 的棋盘上放置 N 个皇后，任何一个都不能吃掉另一个），以及马的遍历路线（在NxN 的棋盘上给马找出一条不重复的走过所有格子的路线）的解。</p>
<div class="section" id="passing-values-into-a-generator">
<h3>向生成器传递值<a class="headerlink" href="#passing-values-into-a-generator" title="永久链接至标题">¶</a></h3>
<p>在 Python 2.4 及之前的版本中，生成器只产生输出。一旦调用生成器的代码创建一个迭代器，就没有办法在函数恢复执行的时候向它传递新的信息。你可以设法实现这个功能，让生成器引用一个全局变量或者一个调用者可以修改的可变对象，但是这些方法都很繁杂。</p>
<p>在 Python 2.5 里有一个简单的将值传递给生成器的方法。<a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> 变成了一个表达式，返回一个可以赋给变量或执行操作的值:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">val</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
<p>我建议你在处理 <code class="docutils literal notranslate"><span class="pre">yield</span></code> 表达式返回值的时候， <strong>总是</strong> 两边写上括号，就像上面的例子一样。括号并不总是必须的，但是比起记住什么时候需要括号，写出来会更容易一点。</p>
<p>（<span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a> 解释了具体的规则，也就是 <code class="docutils literal notranslate"><span class="pre">yield</span></code> 表达式必须括起来，除非是出现在最顶级的赋值表达式的右边。这意味着你可以写 <code class="docutils literal notranslate"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">i</span></code>，但是必须在操作的时候加上括号，就像``val = (yield i) + 12``）</p>
<p>可以调用 <code class="xref py py-meth docutils literal notranslate"><span class="pre">send(value)()</span></code> &lt;generator.send&gt; 方法向生成器发送值。这个方法会恢复执行生成器的代码，然后 <code class="docutils literal notranslate"><span class="pre">yield</span></code> 表达式返回特定的值。如果调用普通的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__`方法，``yield`()</span></code> 会返回 <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>这里有一个简单的每次加1的计数器，并允许改变内部计数器的值。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">counter</span><span class="p">(</span><span class="n">maximum</span><span class="p">):</span>
    <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">while</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">maximum</span><span class="p">:</span>
        <span class="n">val</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">i</span><span class="p">)</span>
        <span class="c1"># If value provided, change counter</span>
        <span class="k">if</span> <span class="n">val</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">i</span> <span class="o">=</span> <span class="n">val</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>这是改变计数器的一个示例</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">it</span> <span class="o">=</span> <span class="n">counter</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>  
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>  
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>  
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="mi">8</span><span class="p">)</span>  
<span class="go">8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>  
<span class="go">9</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>  
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;t.py&quot;</span>, line <span class="m">15</span>, in <span class="n">&lt;module&gt;</span>
    <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gr">StopIteration</span>
</pre></div>
</div>
<p>因为 <code class="docutils literal notranslate"><span class="pre">yield</span></code> 很多时候会返回 <code class="docutils literal notranslate"><span class="pre">None</span></code>，所以你应该总是检查这个情况。不要在表达式中使用 <code class="docutils literal notranslate"><span class="pre">yield</span></code> 的值，除非你确定 <a class="reference internal" href="../reference/expressions.html#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> 是唯一的用来恢复你的生成器函数的方法。</p>
<p>除了 <a class="reference internal" href="../reference/expressions.html#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> 之外，生成器还有两个其他的方法:</p>
<ul>
<li><p><a class="reference internal" href="../reference/expressions.html#generator.throw" title="generator.throw"><code class="xref py py-meth docutils literal notranslate"><span class="pre">throw(type,</span> <span class="pre">value=None,</span> <span class="pre">traceback=None)</span></code></a> 用于在生成器内部抛出异常；这个异常会在生成器暂停执行的时候由 <code class="docutils literal notranslate"><span class="pre">yield</span></code> 表达式抛出。</p></li>
<li><p><a class="reference internal" href="../reference/expressions.html#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">generator.close()</span></code></a> 会在生成器内部抛出 <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> 异常来结束迭代。当接收到这个异常时，生成器的代码会抛出 <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> 或者 <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>；捕捉这个异常作其他处理是非法的，并会出发 <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>。<a class="reference internal" href="../reference/expressions.html#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> 也会在 Python 垃圾回收器回收生成器的时候调用。</p>
<p>如果你要在 <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> 发生的时候清理代码，我建议使用 <code class="docutils literal notranslate"><span class="pre">try:</span> <span class="pre">...</span> <span class="pre">finally:</span></code> 组合来代替 <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a>。</p>
</li>
</ul>
<p>这些改变的累积效应是，让生成器从单向的信息生产者变成了既是生产者，又是消费者。</p>
<p>生成器也可以成为 <strong>协程</strong> ，一种更广义的子过程形式。子过程可以从一个地方进入，然后从另一个地方退出（从函数的顶端进入，从 <code class="docutils literal notranslate"><span class="pre">return</span></code> 语句退出），而协程可以进入，退出，然后在很多不同的地方恢复（<code class="docutils literal notranslate"><span class="pre">yield</span></code> 语句）。</p>
</div>
</div>
<div class="section" id="built-in-functions">
<h2>内置函数<a class="headerlink" href="#built-in-functions" title="永久链接至标题">¶</a></h2>
<p>我们可以看看迭代器常常用到的函数的更多细节。</p>
<p>Python 内置的两个函数 <a class="reference internal" href="../library/functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a> 和 <a class="reference internal" href="../library/functions.html#filter" title="filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a> 复制了生成器表达式的两个特性:</p>
<dl>
<dt><a class="reference internal" href="../library/functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map(f,</span> <span class="pre">iterA,</span> <span class="pre">iterB,</span> <span class="pre">...)</span></code></a> 返回一个遍历序列的迭代器</dt><dd><p><code class="docutils literal notranslate"><span class="pre">f(iterA[0],</span> <span class="pre">iterB[0]),</span> <span class="pre">f(iterA[1],</span> <span class="pre">iterB[1]),</span> <span class="pre">f(iterA[2],</span> <span class="pre">iterB[2]),</span> <span class="pre">...</span></code>.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">upper</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">s</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
</pre></div>
</div>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="n">upper</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;sentence&#39;</span><span class="p">,</span> <span class="s1">&#39;fragment&#39;</span><span class="p">]))</span>
<span class="go">[&#39;SENTENCE&#39;, &#39;FRAGMENT&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">upper</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;sentence&#39;</span><span class="p">,</span> <span class="s1">&#39;fragment&#39;</span><span class="p">]]</span>
<span class="go">[&#39;SENTENCE&#39;, &#39;FRAGMENT&#39;]</span>
</pre></div>
</div>
</dd>
</dl>
<p>你当然也可以用列表推导式达到同样的效果。</p>
<p><a class="reference internal" href="../library/functions.html#filter" title="filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter(predicate,</span> <span class="pre">iter)</span></code></a> 返回一个遍历序列中满足指定条件的元素的迭代器，和列表推导式的功能相似。 <strong>predicate</strong> （谓词）是一个在特定条件下返回真值的函数；要使用函数 <a class="reference internal" href="../library/functions.html#filter" title="filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a>，谓词函数必须只能接受一个参数。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">is_even</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="p">(</span><span class="n">x</span> <span class="o">%</span> <span class="mi">2</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span>
</pre></div>
</div>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">filter</span><span class="p">(</span><span class="n">is_even</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)))</span>
<span class="go">[0, 2, 4, 6, 8]</span>
</pre></div>
</div>
<p>这也可以写成列表推导式:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="k">if</span> <span class="n">is_even</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>
<span class="go">[0, 2, 4, 6, 8]</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate(iter,</span> <span class="pre">start=0)</span></code></a> 计数可迭代对象中的元素，然后返回包含每个计数（从 <strong>start</strong> 开始）和元素两个值的元组。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">([</span><span class="s1">&#39;subject&#39;</span><span class="p">,</span> <span class="s1">&#39;verb&#39;</span><span class="p">,</span> <span class="s1">&#39;object&#39;</span><span class="p">]):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
<span class="go">(0, &#39;subject&#39;)</span>
<span class="go">(1, &#39;verb&#39;)</span>
<span class="go">(2, &#39;object&#39;)</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a> 常常用于遍历列表并记录达到特定条件时的下标:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;data.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="o">==</span> <span class="s1">&#39;&#39;</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Blank line at line #</span><span class="si">%i</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted(iterable,</span> <span class="pre">key=None,</span> <span class="pre">reverse=False)</span></code></a> 会将 iterable 中的元素收集到一个列表中，然后排序并返回结果。其中 <em>key</em> 和 <em>reverse</em> 参数会传递给所创建列表的 <a class="reference internal" href="../library/stdtypes.html#list.sort" title="list.sort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code></a> 方法。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">random</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Generate 8 random numbers between [0, 10000)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rand_list</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10000</span><span class="p">),</span> <span class="mi">8</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rand_list</span>  
<span class="go">[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">rand_list</span><span class="p">)</span>  
<span class="go">[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">rand_list</span><span class="p">,</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>  
<span class="go">[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]</span>
</pre></div>
</div>
<p>（对排序更详细的讨论可参见 <a class="reference internal" href="sorting.html#sortinghowto"><span class="std std-ref">排序指南</span></a>。）</p>
<p>内置函数 <a class="reference internal" href="../library/functions.html#any" title="any"><code class="xref py py-func docutils literal notranslate"><span class="pre">any(iter)</span></code></a> 和 <a class="reference internal" href="../library/functions.html#all" title="all"><code class="xref py py-func docutils literal notranslate"><span class="pre">all(iter)</span></code></a> 会查看一个可迭代对象内容的逻辑值。<a class="reference internal" href="../library/functions.html#any" title="any"><code class="xref py py-func docutils literal notranslate"><span class="pre">any()</span></code></a> 在可迭代对象中任意一个元素为真时返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，而 <a class="reference internal" href="../library/functions.html#all" title="all"><code class="xref py py-func docutils literal notranslate"><span class="pre">all()</span></code></a> 在所有元素为真时返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">any</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">])</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">any</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">])</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">any</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">])</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">all</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">])</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">all</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">])</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">all</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">])</span>
<span class="go">True</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip(iterA,</span> <span class="pre">iterB,</span> <span class="pre">...)</span></code></a> 从每个可迭代对象中选取单个元素组成列表并返回:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">zip</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">],</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
</pre></div>
</div>
<p>它并不会在内存创建一个列表并因此在返回前而耗尽输入的迭代器；相反，只有在被请求的时候元组才会创建并返回。（这种行为的技术术语叫惰性计算，参见 <a class="reference external" href="https://en.wikipedia.org/wiki/Lazy_evaluation">lazy evaluation</a>.）</p>
<p>这个迭代器设计用于长度相同的可迭代对象。如果可迭代对象的长度不一致，返回的数据流的长度会和最短的可迭代对象相同</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">zip</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">],</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>然而，你应该避免这种情况，因为所有从更长的迭代器中取出的元素都会被丢弃。这意味着之后你也无法冒着跳过被丢弃元素的风险来继续使用这个迭代器。</p>
</div>
<div class="section" id="the-itertools-module">
<h2>itertools 模块<a class="headerlink" href="#the-itertools-module" title="永久链接至标题">¶</a></h2>
<p><a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> 模块包含很多常用的迭代器以及用来组合迭代器的函数。本节会用些小的例子来介绍这个模块的内容。</p>
<p>这个模块里的函数大致可以分为几类：</p>
<ul class="simple">
<li><p>从已有的迭代器创建新的迭代器的函数。</p></li>
<li><p>接受迭代器元素作为参数的函数。</p></li>
<li><p>选取部分迭代器输出的函数。</p></li>
<li><p>给迭代器输出分组的函数。</p></li>
</ul>
<div class="section" id="creating-new-iterators">
<h3>创建新的迭代器<a class="headerlink" href="#creating-new-iterators" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="../library/itertools.html#itertools.count" title="itertools.count"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.count(start,</span> <span class="pre">step)</span></code></a> 返回一个等分的无限数据流。初始值默认为0，间隔默认为1，你也选择可以指定初始值和间隔:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">()</span> <span class="o">=&gt;</span>
  <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="o">...</span>
<span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="mi">10</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">13</span><span class="p">,</span> <span class="mi">14</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="mi">16</span><span class="p">,</span> <span class="mi">17</span><span class="p">,</span> <span class="mi">18</span><span class="p">,</span> <span class="mi">19</span><span class="p">,</span> <span class="o">...</span>
<span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="mi">10</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">25</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">35</span><span class="p">,</span> <span class="mi">40</span><span class="p">,</span> <span class="mi">45</span><span class="p">,</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">55</span><span class="p">,</span> <span class="o">...</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/itertools.html#itertools.cycle" title="itertools.cycle"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.cycle(iter)</span></code></a> 保存一份所提供的可迭代对象的副本，并返回一个能产生整个可迭代对象序列的新迭代器。新迭代器会无限重复这些元素。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">cycle</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">])</span> <span class="o">=&gt;</span>
  <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="o">...</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/itertools.html#itertools.repeat" title="itertools.repeat"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.repeat(elem,</span> <span class="pre">[n])</span></code></a> 返回 <em>n</em> 次所提供的元素，当 <em>n</em> 不存在时，返回无数次所提供的元素。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="s1">&#39;abc&#39;</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="o">...</span>
<span class="n">itertools</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="s1">&#39;abc&#39;</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/itertools.html#itertools.chain" title="itertools.chain"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.chain(iterA,</span> <span class="pre">iterB,</span> <span class="pre">...)</span></code></a> 接受任意数量的可迭代对象作为输入，首先返回第一个迭代器的所有元素，然后是第二个的所有元素，如此一直进行下去，直到消耗掉所有输入的可迭代对象。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">chain</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">],</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span> <span class="o">=&gt;</span>
  <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/itertools.html#itertools.islice" title="itertools.islice"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.islice(iter,</span> <span class="pre">[start],</span> <span class="pre">stop,</span> <span class="pre">[step])</span></code></a> 返回一个所输入的迭代器切片的数据流。如果只单独给定 <em>stop</em> 参数的话，它会返回从起始算起 <em>stop</em> 个数量的元素。如果你提供了起始下标 <em>start</em>，你会得到 <em>stop-start</em> 个元素；如果你给定了 <em>step</em> 参数，数据流会跳过相应的元素。和 Python 里的字符串和列表切片不同，你不能在 <em>start</em>, <em>stop</em> 或者 <em>step</em> 这些参数中使用负数。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span> <span class="mi">8</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span>
<span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span>
<span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/itertools.html#itertools.tee" title="itertools.tee"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.tee(iter,</span> <span class="pre">[n])</span></code></a> 可以复制一个迭代器；它返回 <em>n</em> 个能够返回源迭代器内容的独立迭代器。如果你不提供参数 <em>n</em>，默认值为 2。复制迭代器需要保存源迭代器的一部分内容，因此在源迭代器比较大的时候会显著地占用内存；同时，在所有新迭代器中，有一个迭代器会比其他迭代器占用更多的内存。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">tee</span><span class="p">(</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">()</span> <span class="p">)</span> <span class="o">=&gt;</span>
   <span class="n">iterA</span><span class="p">,</span> <span class="n">iterB</span>

<span class="n">where</span> <span class="n">iterA</span> <span class="o">-&gt;</span>
   <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="o">...</span>

<span class="ow">and</span>   <span class="n">iterB</span> <span class="o">-&gt;</span>
   <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="o">...</span>
</pre></div>
</div>
</div>
<div class="section" id="calling-functions-on-elements">
<h3>对元素使用函数<a class="headerlink" href="#calling-functions-on-elements" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> 模块包含一组对应于 Python 操作符的函数。比如 <a class="reference internal" href="../library/operator.html#operator.add" title="operator.add"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.add(a,</span> <span class="pre">b)</span></code></a> （把两个数加起来），<a class="reference internal" href="../library/operator.html#operator.ne" title="operator.ne"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.ne(a,</span> <span class="pre">b)</span></code></a> （和 <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">!=</span> <span class="pre">b</span></code> 相同），以及 <a class="reference internal" href="../library/operator.html#operator.attrgetter" title="operator.attrgetter"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.attrgetter('id')</span></code></a> （返回获取 <code class="docutils literal notranslate"><span class="pre">.id</span></code> 属性的可调用对象）。</p>
<p><a class="reference internal" href="../library/itertools.html#itertools.starmap" title="itertools.starmap"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.starmap(func,</span> <span class="pre">iter)</span></code></a> 假定可迭代对象能够返回一个元组的流，并且利用这些元组作为参数来调用 <em>func</em>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">starmap</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">,</span>
                  <span class="p">[(</span><span class="s1">&#39;/bin&#39;</span><span class="p">,</span> <span class="s1">&#39;python&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;/usr&#39;</span><span class="p">,</span> <span class="s1">&#39;bin&#39;</span><span class="p">,</span> <span class="s1">&#39;java&#39;</span><span class="p">),</span>
                   <span class="p">(</span><span class="s1">&#39;/usr&#39;</span><span class="p">,</span> <span class="s1">&#39;bin&#39;</span><span class="p">,</span> <span class="s1">&#39;perl&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;/usr&#39;</span><span class="p">,</span> <span class="s1">&#39;bin&#39;</span><span class="p">,</span> <span class="s1">&#39;ruby&#39;</span><span class="p">)])</span>
<span class="o">=&gt;</span>
  <span class="o">/</span><span class="nb">bin</span><span class="o">/</span><span class="n">python</span><span class="p">,</span> <span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="nb">bin</span><span class="o">/</span><span class="n">java</span><span class="p">,</span> <span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="nb">bin</span><span class="o">/</span><span class="n">perl</span><span class="p">,</span> <span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="nb">bin</span><span class="o">/</span><span class="n">ruby</span>
</pre></div>
</div>
</div>
<div class="section" id="selecting-elements">
<h3>选择元素<a class="headerlink" href="#selecting-elements" title="永久链接至标题">¶</a></h3>
<p>另外一系列函数根据谓词选取一个迭代器中元素的子集。</p>
<p><a class="reference internal" href="../library/itertools.html#itertools.filterfalse" title="itertools.filterfalse"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.filterfalse(predicate,</span> <span class="pre">iter)</span></code></a> 和  <a class="reference internal" href="../library/functions.html#filter" title="filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a> 相反，返回所有让 predicate 返回 false 的元素:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">filterfalse</span><span class="p">(</span><span class="n">is_even</span><span class="p">,</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">())</span> <span class="o">=&gt;</span>
  <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">13</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="o">...</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/itertools.html#itertools.takewhile" title="itertools.takewhile"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.takewhile(predicate,</span> <span class="pre">iter)</span></code></a> 返回一直让 predicate 返回 true 的元素。一旦 predicate 返回 false，迭代器就会发出终止结果的信号。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">less_than_10</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">10</span>

<span class="n">itertools</span><span class="o">.</span><span class="n">takewhile</span><span class="p">(</span><span class="n">less_than_10</span><span class="p">,</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">())</span> <span class="o">=&gt;</span>
  <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span>

<span class="n">itertools</span><span class="o">.</span><span class="n">takewhile</span><span class="p">(</span><span class="n">is_even</span><span class="p">,</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">())</span> <span class="o">=&gt;</span>
  <span class="mi">0</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/itertools.html#itertools.dropwhile" title="itertools.dropwhile"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.dropwhile(predicate,</span> <span class="pre">iter)</span></code></a> 在 predicate 返回 true 的时候丢弃元素，并且返回可迭代对象的剩余结果。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">dropwhile</span><span class="p">(</span><span class="n">less_than_10</span><span class="p">,</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">())</span> <span class="o">=&gt;</span>
  <span class="mi">10</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">13</span><span class="p">,</span> <span class="mi">14</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="mi">16</span><span class="p">,</span> <span class="mi">17</span><span class="p">,</span> <span class="mi">18</span><span class="p">,</span> <span class="mi">19</span><span class="p">,</span> <span class="o">...</span>

<span class="n">itertools</span><span class="o">.</span><span class="n">dropwhile</span><span class="p">(</span><span class="n">is_even</span><span class="p">,</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">())</span> <span class="o">=&gt;</span>
  <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="o">...</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/itertools.html#itertools.compress" title="itertools.compress"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.compress(data,</span> <span class="pre">selectors)</span></code></a> 接受两个迭代器，然后返回 <em>data</em> 中使相应地 <em>selector</em> 中的元素为真的元素；它会在任一个迭代器耗尽的时候停止:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">compress</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span> <span class="p">[</span><span class="kc">True</span><span class="p">,</span> <span class="kc">True</span><span class="p">,</span> <span class="kc">False</span><span class="p">,</span> <span class="kc">False</span><span class="p">,</span> <span class="kc">True</span><span class="p">])</span> <span class="o">=&gt;</span>
   <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">5</span>
</pre></div>
</div>
</div>
<div class="section" id="combinatoric-functions">
<h3>组合函数<a class="headerlink" href="#combinatoric-functions" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="../library/itertools.html#itertools.combinations" title="itertools.combinations"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.combinations(iterable,</span> <span class="pre">r)</span></code></a> 返回一个迭代器，它能给出输入迭代器中所包含的元素的所有可能的 <em>r</em> 元元组的组合。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">combinations</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span> <span class="mi">2</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>

<span class="n">itertools</span><span class="o">.</span><span class="n">combinations</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span> <span class="mi">3</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
</pre></div>
</div>
<p>每个元组中的元素保持着 <em>可迭代对象</em> 返回他们的顺序。例如，在上面的例子中数字 1 总是会在 2, 3, 4 或 5 前面。一个类似的函数，<a class="reference internal" href="../library/itertools.html#itertools.permutations" title="itertools.permutations"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.permutations(iterable,</span> <span class="pre">r=None)</span></code></a>，取消了保持顺序的限制，返回所有可能的长度为 <em>r</em> 的排列:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">permutations</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span> <span class="mi">2</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>

<span class="n">itertools</span><span class="o">.</span><span class="n">permutations</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">])</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="o">...</span>
  <span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>如果你不提供 <em>r</em> 参数的值，它会使用可迭代对象的长度，也就是说会排列所有的元素。</p>
<p>注意这些函数会输出所有可能的位置组合，并不要求 <em>可迭代对象</em> 的内容不重复:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">permutations</span><span class="p">(</span><span class="s1">&#39;aba&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">),</span>
  <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>同一个元组 <code class="docutils literal notranslate"><span class="pre">('a',</span> <span class="pre">'a',</span> <span class="pre">'b')</span></code> 出现了两次，但是两个 'a' 字符来自不同的位置。</p>
<p><a class="reference internal" href="../library/itertools.html#itertools.combinations_with_replacement" title="itertools.combinations_with_replacement"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.combinations_with_replacement(iterable,</span> <span class="pre">r)</span></code></a> 函数放松了一个不同的限制：元组中的元素可以重复。从概念讲，为每个元组第一个位置选取一个元素，然后在选择第二个元素前替换掉它。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">combinations_with_replacement</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span> <span class="mi">2</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
  <span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="grouping-elements">
<h3>为元素分组<a class="headerlink" href="#grouping-elements" title="永久链接至标题">¶</a></h3>
<p>我要讨论的最后一个函数，<a class="reference internal" href="../library/itertools.html#itertools.groupby" title="itertools.groupby"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.groupby(iter,key_func=None)</span></code></a>，是最复杂的函数。 <code class="docutils literal notranslate"><span class="pre">key_func(elem)</span></code> 是一个可以对迭代器返回的每个元素计算键值的函数。 如果你不提供这个键值函数，它就会简化成每个元素自身。</p>
<p><a class="reference internal" href="../library/itertools.html#itertools.groupby" title="itertools.groupby"><code class="xref py py-func docutils literal notranslate"><span class="pre">groupby()</span></code></a> 从所依据的可迭代对象中连续地收集具有相同值的元素，然后返回一个长度为2的元组的数据流, 每个元组包含键值以及对应这个键值的元素所组成的迭代器。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">city_list</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;Decatur&#39;</span><span class="p">,</span> <span class="s1">&#39;AL&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Huntsville&#39;</span><span class="p">,</span> <span class="s1">&#39;AL&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Selma&#39;</span><span class="p">,</span> <span class="s1">&#39;AL&#39;</span><span class="p">),</span>
             <span class="p">(</span><span class="s1">&#39;Anchorage&#39;</span><span class="p">,</span> <span class="s1">&#39;AK&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Nome&#39;</span><span class="p">,</span> <span class="s1">&#39;AK&#39;</span><span class="p">),</span>
             <span class="p">(</span><span class="s1">&#39;Flagstaff&#39;</span><span class="p">,</span> <span class="s1">&#39;AZ&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Phoenix&#39;</span><span class="p">,</span> <span class="s1">&#39;AZ&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Tucson&#39;</span><span class="p">,</span> <span class="s1">&#39;AZ&#39;</span><span class="p">),</span>
             <span class="o">...</span>
            <span class="p">]</span>

<span class="k">def</span> <span class="nf">get_state</span><span class="p">(</span><span class="n">city_state</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">city_state</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>

<span class="n">itertools</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="n">city_list</span><span class="p">,</span> <span class="n">get_state</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;AL&#39;</span><span class="p">,</span> <span class="n">iterator</span><span class="o">-</span><span class="mi">1</span><span class="p">),</span>
  <span class="p">(</span><span class="s1">&#39;AK&#39;</span><span class="p">,</span> <span class="n">iterator</span><span class="o">-</span><span class="mi">2</span><span class="p">),</span>
  <span class="p">(</span><span class="s1">&#39;AZ&#39;</span><span class="p">,</span> <span class="n">iterator</span><span class="o">-</span><span class="mi">3</span><span class="p">),</span> <span class="o">...</span>

<span class="n">where</span>
<span class="n">iterator</span><span class="o">-</span><span class="mi">1</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;Decatur&#39;</span><span class="p">,</span> <span class="s1">&#39;AL&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Huntsville&#39;</span><span class="p">,</span> <span class="s1">&#39;AL&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Selma&#39;</span><span class="p">,</span> <span class="s1">&#39;AL&#39;</span><span class="p">)</span>
<span class="n">iterator</span><span class="o">-</span><span class="mi">2</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;Anchorage&#39;</span><span class="p">,</span> <span class="s1">&#39;AK&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Nome&#39;</span><span class="p">,</span> <span class="s1">&#39;AK&#39;</span><span class="p">)</span>
<span class="n">iterator</span><span class="o">-</span><span class="mi">3</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;Flagstaff&#39;</span><span class="p">,</span> <span class="s1">&#39;AZ&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Phoenix&#39;</span><span class="p">,</span> <span class="s1">&#39;AZ&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Tucson&#39;</span><span class="p">,</span> <span class="s1">&#39;AZ&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/itertools.html#itertools.groupby" title="itertools.groupby"><code class="xref py py-func docutils literal notranslate"><span class="pre">groupby()</span></code></a> 假定了所依据的可迭代对象的内容已经根据键值排序。注意，返回的迭代器也会使用所依据的可迭代对象，所以在请求迭代器 2和相应的键之前你必须先消耗迭代器 1 的结果。</p>
</div>
</div>
<div class="section" id="the-functools-module">
<h2>functools 模块<a class="headerlink" href="#the-functools-module" title="永久链接至标题">¶</a></h2>
<p>Python 2.5 中的 <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> 模块包含了一些高阶函数。 <strong>高阶函数</strong> 接受一个或多个函数作为输入，返回新的函数。 这个模块中最有用的工具是 <a class="reference internal" href="../library/functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a> 函数。</p>
<p>对于用函数式风格编写的程序，有时你会希望通过给定部分参数，将已有的函数构变形称新的函数。考虑一个 Python 函数 <code class="docutils literal notranslate"><span class="pre">f(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code>；你希望创建一个和 <code class="docutils literal notranslate"><span class="pre">f(1,</span> <span class="pre">b,</span> <span class="pre">c)</span></code> 等价的新函数 <code class="docutils literal notranslate"><span class="pre">g(b,</span> <span class="pre">c)</span></code>；也就是说你给定了 <code class="docutils literal notranslate"><span class="pre">f()</span></code> 的一个参数的值。这就是所谓的“部分函数应用”。</p>
<p><a class="reference internal" href="../library/functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">partial()</span></code></a> 接受参数 <code class="docutils literal notranslate"><span class="pre">(function,</span> <span class="pre">arg1,</span> <span class="pre">arg2,</span> <span class="pre">...,</span> <span class="pre">kwarg1=value1,</span> <span class="pre">kwarg2=value2)</span></code>。它会返回一个可调用的对象，所以你能够直接调用这个结果以使用给定参数的 <code class="docutils literal notranslate"><span class="pre">function</span></code>。</p>
<p>这里有一个很小但很现实的例子:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">functools</span>

<span class="k">def</span> <span class="nf">log</span><span class="p">(</span><span class="n">message</span><span class="p">,</span> <span class="n">subsystem</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Write the contents of &#39;message&#39; to the specified subsystem.&quot;&quot;&quot;</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%s</span><span class="s1">: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">subsystem</span><span class="p">,</span> <span class="n">message</span><span class="p">))</span>
    <span class="o">...</span>

<span class="n">server_log</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="n">log</span><span class="p">,</span> <span class="n">subsystem</span><span class="o">=</span><span class="s1">&#39;server&#39;</span><span class="p">)</span>
<span class="n">server_log</span><span class="p">(</span><span class="s1">&#39;Unable to open socket&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/functools.html#functools.reduce" title="functools.reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.reduce(func,</span> <span class="pre">iter,</span> <span class="pre">[initial_value])</span></code></a> 持续地在可迭代对象的所有元素上执行操作，因此它不能够用在无限的可迭代对象上。<em>func</em> 必须是一个接受两个元素并返回一个值的函数。<a class="reference internal" href="../library/functools.html#functools.reduce" title="functools.reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.reduce()</span></code></a> 接受迭代器返回的前两个元素 A 和 B 并计算 <code class="docutils literal notranslate"><span class="pre">func(A,</span> <span class="pre">B)</span></code> 。然后它会请求第三个元素，C，计算 <code class="docutils literal notranslate"><span class="pre">func(func(A,</span> <span class="pre">B),</span> <span class="pre">C)</span></code>，然后把这个结果再和第四个元素组合并返回，如此继续下去直到消耗整个可迭代对象。如果输入的可迭代对象完全不返回任何值，<a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> 异常就会抛出。如果提供了初值(initial value)，它会被用作起始值，也就是先计算 <code class="docutils literal notranslate"><span class="pre">func(initial_value,</span> <span class="pre">A)</span></code> 。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">operator</span><span class="o">,</span> <span class="nn">functools</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">functools</span><span class="o">.</span><span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">concat</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;A&#39;</span><span class="p">,</span> <span class="s1">&#39;BB&#39;</span><span class="p">,</span> <span class="s1">&#39;C&#39;</span><span class="p">])</span>
<span class="go">&#39;ABBC&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">functools</span><span class="o">.</span><span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">concat</span><span class="p">,</span> <span class="p">[])</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">TypeError</span>: <span class="n">reduce() of empty sequence with no initial value</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">functools</span><span class="o">.</span><span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">6</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">functools</span><span class="o">.</span><span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">,</span> <span class="p">[],</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">1</span>
</pre></div>
</div>
<p>如果你在 <a class="reference internal" href="../library/functools.html#functools.reduce" title="functools.reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.reduce()</span></code></a> 中使用 <a class="reference internal" href="../library/operator.html#operator.add" title="operator.add"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.add()</span></code></a>，你就会把可迭代对象中的所有元素加起来.这种情况非常常见, 所以 Python 有一个特殊的内置函数 <a class="reference internal" href="../library/functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a>:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">functools</span><span class="o">,</span> <span class="nn">operator</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">functools</span><span class="o">.</span><span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">add</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">],</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">])</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">([])</span>
<span class="go">0</span>
</pre></div>
</div>
<p>不过, 对于很多使用 <a class="reference internal" href="../library/functools.html#functools.reduce" title="functools.reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.reduce()</span></code></a> 的情形, 使用明显的 <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> 循环会更清晰:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">functools</span>
<span class="c1"># Instead of:</span>
<span class="n">product</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="mi">1</span><span class="p">)</span>

<span class="c1"># You can write:</span>
<span class="n">product</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]:</span>
    <span class="n">product</span> <span class="o">*=</span> <span class="n">i</span>
</pre></div>
</div>
<p>一个相关的函数是 <a class="reference internal" href="../library/itertools.html#itertools.accumulate" title="itertools.accumulate"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.accumulate(iterable,</span> <span class="pre">func=operator.add)</span></code></a> 。它执行同样的计算, 不过相对于只返回最终结果，<code class="xref py py-func docutils literal notranslate"><span class="pre">accumulate()</span></code> 会返回一个迭代器来输出所有中间结果:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">accumulate</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">])</span> <span class="o">=&gt;</span>
  <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">15</span>

<span class="n">itertools</span><span class="o">.</span><span class="n">accumulate</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span> <span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">24</span><span class="p">,</span> <span class="mi">120</span>
</pre></div>
</div>
<div class="section" id="the-operator-module">
<h3>operator 模块<a class="headerlink" href="#the-operator-module" title="永久链接至标题">¶</a></h3>
<p>前面已经提到了 <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> 模块。它包含一系列对应于 Python 操作符的函数。在函数式风格的代码中，这些函数通常很有用，可以帮你省下不少时间，避免写一些琐碎的仅仅执行一个简单操作的函数。</p>
<p>这个模块里的一些函数：</p>
<ul class="simple">
<li><p>数学运算： <code class="docutils literal notranslate"><span class="pre">add()</span></code>，<code class="docutils literal notranslate"><span class="pre">sub()</span></code>，<code class="docutils literal notranslate"><span class="pre">mul()</span></code>，<code class="docutils literal notranslate"><span class="pre">floordiv()</span></code>，<code class="docutils literal notranslate"><span class="pre">abs()</span></code>， ...</p></li>
<li><p>逻辑运算： <code class="docutils literal notranslate"><span class="pre">not_()</span></code>，<code class="docutils literal notranslate"><span class="pre">truth()</span></code>。</p></li>
<li><p>位运算： <code class="docutils literal notranslate"><span class="pre">and_()</span></code>，<code class="docutils literal notranslate"><span class="pre">or_()</span></code>，<code class="docutils literal notranslate"><span class="pre">invert()</span></code>。</p></li>
<li><p>比较： <code class="docutils literal notranslate"><span class="pre">eq()</span></code>，<code class="docutils literal notranslate"><span class="pre">ne()</span></code>，<code class="docutils literal notranslate"><span class="pre">lt()</span></code>，<code class="docutils literal notranslate"><span class="pre">le()</span></code>，<code class="docutils literal notranslate"><span class="pre">gt()</span></code>，和 <code class="docutils literal notranslate"><span class="pre">ge()</span></code>。</p></li>
<li><p>确认对象： <code class="docutils literal notranslate"><span class="pre">is_()</span></code>，<code class="docutils literal notranslate"><span class="pre">is_not()</span></code>。</p></li>
</ul>
<p>全部函数列表可以参考 operator 模块的文档。</p>
</div>
</div>
<div class="section" id="small-functions-and-the-lambda-expression">
<h2>小函数和 lambda 表达式<a class="headerlink" href="#small-functions-and-the-lambda-expression" title="永久链接至标题">¶</a></h2>
<p>编写函数式风格程序时，你会经常需要很小的函数，作为谓词函数或者以某种方式来组合元素。</p>
<p>如果合适的 Python 内置的或者其他模块中的函数，你就一点也不需要定义新的函数:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">stripped_lines</span> <span class="o">=</span> <span class="p">[</span><span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">lines</span><span class="p">]</span>
<span class="n">existing_files</span> <span class="o">=</span> <span class="nb">filter</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">,</span> <span class="n">file_list</span><span class="p">)</span>
</pre></div>
</div>
<p>如果不存在你需要的函数，你就必须自己编写。一个编写小函数的方式是使用 <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> 表达式。<code class="docutils literal notranslate"><span class="pre">lambda</span></code> 接受一组参数以及组合这些参数的表达式，它会创建一个返回表达式值的匿名函数:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">adder</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">:</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span>

<span class="n">print_assign</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">:</span> <span class="n">name</span> <span class="o">+</span> <span class="s1">&#39;=&#39;</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>另一种替代方案就是通常的使用 <code class="docutils literal notranslate"><span class="pre">def</span></code> 语句来定义函数:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">adder</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>

<span class="k">def</span> <span class="nf">print_assign</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">name</span> <span class="o">+</span> <span class="s1">&#39;=&#39;</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>哪一种更受青睐呢？这是一个风格问题；我通常的做法是避免使用 <code class="docutils literal notranslate"><span class="pre">lambda</span></code>。</p>
<p>我这么偏好的一个原因是，<code class="docutils literal notranslate"><span class="pre">lambda</span></code> 能够定义的函数非常受限。函数的结果必须能够作为单独的表达式来计算，这意味着你不能使用多路 <code class="docutils literal notranslate"><span class="pre">if...</span> <span class="pre">elif...</span> <span class="pre">else</span></code> 比较，或者 <code class="docutils literal notranslate"><span class="pre">try...</span> <span class="pre">except</span></code> 语句。如果你尝试在 <code class="docutils literal notranslate"><span class="pre">lambda</span></code> 语句中做太多事情，你最终会把表达式过于复杂以至于难以阅读。你能快速的说出下面的代码做了什么事情吗？:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">functools</span>
<span class="n">total</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">b</span><span class="p">[</span><span class="mi">1</span><span class="p">]),</span> <span class="n">items</span><span class="p">)[</span><span class="mi">1</span><span class="p">]</span>
</pre></div>
</div>
<p>你可以弄明白，不过要花上时间来理清表达式来搞清楚发生了什么。使用一个简短的嵌套的 <code class="docutils literal notranslate"><span class="pre">def</span></code> 语句可以让情况变得更好:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">functools</span>
<span class="k">def</span> <span class="nf">combine</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">b</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>

<span class="n">total</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">reduce</span><span class="p">(</span><span class="n">combine</span><span class="p">,</span> <span class="n">items</span><span class="p">)[</span><span class="mi">1</span><span class="p">]</span>
</pre></div>
</div>
<p>如果我仅仅使用一个 <code class="docutils literal notranslate"><span class="pre">for</span></code> 循环会更好:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">total</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">for</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="ow">in</span> <span class="n">items</span><span class="p">:</span>
    <span class="n">total</span> <span class="o">+=</span> <span class="n">b</span>
</pre></div>
</div>
<p>或者使用内置的 <a class="reference internal" href="../library/functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a> 和一个生成器表达式:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">total</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">b</span> <span class="k">for</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="ow">in</span> <span class="n">items</span><span class="p">)</span>
</pre></div>
</div>
<p>许多使用 <a class="reference internal" href="../library/functools.html#functools.reduce" title="functools.reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.reduce()</span></code></a> 的情形可以更清晰地写成 <code class="docutils literal notranslate"><span class="pre">for</span></code> 循环的形式。</p>
<p>Fredrik Lundh 曾经建议以下一组规则来重构 <code class="docutils literal notranslate"><span class="pre">lambda</span></code> 的使用:</p>
<ol class="arabic simple">
<li><p>写一个 lambda 函数。</p></li>
<li><p>写一句注释来说明这个 lambda 究竟干了什么。</p></li>
<li><p>研究一会这个注释，然后想出一个抓住注释本质的名字。</p></li>
<li><p>用这个名字，把这个 lambda 改写成 def 语句。</p></li>
<li><p>把注释去掉。</p></li>
</ol>
<p>我非常喜欢这些规则，不过你完全有权利争辩这种消除 lambda 的风格是不是更好。</p>
</div>
<div class="section" id="revision-history-and-acknowledgements">
<h2>修订记录和致谢<a class="headerlink" href="#revision-history-and-acknowledgements" title="永久链接至标题">¶</a></h2>
<p>作者要感谢以下人员对本文各种草稿给予的建议，更正和协助：Ian Bicking,Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell,Leandro Lameiro, Jussi Salmela, Collin Winter, Blake Winton。</p>
<p>0.1 版: 2006 年 6 月 30 日发布。</p>
<p>0.11 版: 2006 年 7 月 1 日发布。 修正拼写错误。</p>
<p>0.2 版: 2006 年 7 月 10 日发布。 将 genexp 与 listcomp 两节合二为一。 修正拼写错误。</p>
<p>0.21 版: 加入了 tutor 邮件列表中建议的更多参考文件。</p>
<p>0.30 版: 添加了有关 <code class="docutils literal notranslate"><span class="pre">functional</span></code> 模块的小节，由 Collin Winter 撰写；添加了有关 operator 模块的简短小节；其他少量修改。</p>
</div>
<div class="section" id="references">
<h2>参考文献<a class="headerlink" href="#references" title="永久链接至标题">¶</a></h2>
<div class="section" id="general">
<h3>通用文献<a class="headerlink" href="#general" title="永久链接至标题">¶</a></h3>
<p><strong>Structure and Interpretation of Computer Programs</strong>, Harold Abelson, Gerald Jay Sussman 和 Julie Sussman 著。全文可见 <a class="reference external" href="https://mitpress.mit.edu/sicp/">https://mitpress.mit.edu/sicp/</a> 。在这部计算机科学的经典教科书中，第二和第三章讨论了使用序列和流来组织程序内部的数据传递。书中的示例采用 Scheme 语言，但其中这些章节中描述的很多设计方法同样适用于函数式风格的 Python 代码。</p>
<p><a class="reference external" href="http://www.defmacro.org/ramblings/fp.html">http://www.defmacro.org/ramblings/fp.html</a>: 一个使用 Java 示例的函数式编程的总体介绍，有很长的历史说明。</p>
<p><a class="reference external" href="https://en.wikipedia.org/wiki/Functional_programming">https://en.wikipedia.org/wiki/Functional_programming</a>: 一般性的函数式编程的 Wikipedia 条目。</p>
<p><a class="reference external" href="https://en.wikipedia.org/wiki/Coroutine">https://en.wikipedia.org/wiki/Coroutine</a>: 协程条目。</p>
<p><a class="reference external" href="https://en.wikipedia.org/wiki/Currying">https://en.wikipedia.org/wiki/Currying</a>: 函数柯里化条目。</p>
</div>
<div class="section" id="python-specific">
<h3>Python 相关<a class="headerlink" href="#python-specific" title="永久链接至标题">¶</a></h3>
<p><a class="reference external" href="http://gnosis.cx/TPiP/">http://gnosis.cx/TPiP/</a>：David Mertz 书中的第一章 <cite>Text Processing in Python</cite>，&quot;Utilizing Higher-Order Functions in Text Processing&quot; 标题部分讨论了文本处理的函数式编程。</p>
<p>Mertz 还在 IBM 的 DeveloperWorks 站点上针对函数式编程撰写了一系列共 3 篇文章；参见 <a class="reference external" href="https://developer.ibm.com/articles/l-prog/">part 1</a>, <a class="reference external" href="https://developer.ibm.com/tutorials/l-prog2/">part 2</a> 和 <a class="reference external" href="https://developer.ibm.com/tutorials/l-prog3/">part 3</a>,</p>
</div>
<div class="section" id="python-documentation">
<h3>Python 文档<a class="headerlink" href="#python-documentation" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> 模块文档。</p>
<p><a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> 模块文档。</p>
<p><a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> 模块文档。</p>
<p><span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0289"><strong>PEP 289</strong></a>: &quot;Generator Expressions&quot;</p>
<p><span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a>: &quot;Coroutines via Enhanced Generators&quot; 描述了 Python 2.5 中新的生成器特性。</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">目录</a></h3>
  <ul>
<li><a class="reference internal" href="#">函数式编程指引</a><ul>
<li><a class="reference internal" href="#introduction">概述</a><ul>
<li><a class="reference internal" href="#formal-provability">形式证明</a></li>
<li><a class="reference internal" href="#modularity">模块化</a></li>
<li><a class="reference internal" href="#ease-of-debugging-and-testing">易于调试和测试</a></li>
<li><a class="reference internal" href="#composability">组合性</a></li>
</ul>
</li>
<li><a class="reference internal" href="#iterators">迭代器</a><ul>
<li><a class="reference internal" href="#data-types-that-support-iterators">支持迭代器的数据类型</a></li>
</ul>
</li>
<li><a class="reference internal" href="#generator-expressions-and-list-comprehensions">生成器表达式和列表推导式</a></li>
<li><a class="reference internal" href="#generators">生成器</a><ul>
<li><a class="reference internal" href="#passing-values-into-a-generator">向生成器传递值</a></li>
</ul>
</li>
<li><a class="reference internal" href="#built-in-functions">内置函数</a></li>
<li><a class="reference internal" href="#the-itertools-module">itertools 模块</a><ul>
<li><a class="reference internal" href="#creating-new-iterators">创建新的迭代器</a></li>
<li><a class="reference internal" href="#calling-functions-on-elements">对元素使用函数</a></li>
<li><a class="reference internal" href="#selecting-elements">选择元素</a></li>
<li><a class="reference internal" href="#combinatoric-functions">组合函数</a></li>
<li><a class="reference internal" href="#grouping-elements">为元素分组</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-functools-module">functools 模块</a><ul>
<li><a class="reference internal" href="#the-operator-module">operator 模块</a></li>
</ul>
</li>
<li><a class="reference internal" href="#small-functions-and-the-lambda-expression">小函数和 lambda 表达式</a></li>
<li><a class="reference internal" href="#revision-history-and-acknowledgements">修订记录和致谢</a></li>
<li><a class="reference internal" href="#references">参考文献</a><ul>
<li><a class="reference internal" href="#general">通用文献</a></li>
<li><a class="reference internal" href="#python-specific">Python 相关</a></li>
<li><a class="reference internal" href="#python-documentation">Python 文档</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="descriptor.html"
                        title="上一章">实现描述器</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="logging.html"
                        title="下一章">日志 HOWTO</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">提交 Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.7/Doc/howto/functional.rst"
            rel="nofollow">显示源代码
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="logging.html" title="日志 HOWTO"
             >下一页</a> |</li>
        <li class="right" >
          <a href="descriptor.html" title="实现描述器"
             >上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 常用指引</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">版权所有</a> 2001-2020, Python Software Foundation.
    <br />
    Python 软件基金会是一个非盈利组织。
    <a href="https://www.python.org/psf/donations/">请捐助。</a>
    <br />
    最后更新于 6月 29, 2020.
    <a href="../bugs.html">发现了问题</a>？
    <br />
    使用<a href="http://sphinx.pocoo.org/">Sphinx</a>2.3.1 创建。
    </div>

  </body>
</html>